<template>
  <div class="relative h-full w-full">
    <div
      v-if="showBg"
      class="z-1 absolute left-0 top-0 flex h-full w-full items-center justify-center"
    >
      暂无数据
    </div>
    <div class="relative z-10 h-full w-full bg-transparent" :id="id"></div>
  </div>
</template>

<script setup lang="tsx">
import {
  computed,
  onMounted,
  onUnmounted,
  ref,
  toRaw,
  useId,
  watch,
} from 'vue';
import { useEventSource } from '@boeyo/hooks';
import { useUserStore } from '@boeyo/portal';
import { realDataChart } from '@/utils/index';

const showBg = ref(true);
const userStore = useUserStore();

const id = useId();

const props = defineProps({
  channel: {
    type: Array,
    default: [],
  },
  presentation: {
    type: Array,
    default: [],
  },
  instanceOptions: {
    type: Object,
    default: () => {},
  },
  deviceInfo: {
    type: Array,
    default: () => [],
  },
});
const isHighPassFilter = computed(() => props.presentation[0] !== 'value');
let intensity = 0;
const samplingRate = 100;
const code = computed(() => props.deviceInfo[0]);

const channels = computed(() => {
  return props.instanceOptions.channelList
    .filter((item) => props.channel.includes(item.value))
    .map((cur, index) => {
      const { value, color } = cur;
      return {
        color,
        name: value,
        yName: '单位: 度(°)',
        grid: {
          show: true,
          top: `${30 * index + 7} + %`,
          left: '5%',
          right: '3%',
          height: `${100 / 3 - 10}%`,
        },
      };
    });
});

let renderChart;
let updateChartConfig;

onMounted(() => {
  const { renderChart: _renderChart, updateChartConfig: _updateChartConfig } =
    realDataChart({
      target: document.getElementById(id),
      title: `设备标识：${code.value} | 采样率：${samplingRate} `,
      direction: 'vertical',
      channels: toRaw(channels.value),
    });
  renderChart = _renderChart;
  updateChartConfig = _updateChartConfig;
  connect();
});

const formatData = (cb) => {
  let data = {};
  const checkData = () => {
    let flag = false;
    if (Object.keys(data).length !== 3) return false;
    Object.values(data)
      .map((item) => item[0][0])
      .reduce((prev, cur) => {
        flag = prev === cur;
        return cur;
      });
    return flag;
  };
  const push = (_data) => {
    Object.keys(_data).forEach((_key) => {
      let key;
      switch (_key) {
        case 'Z':
          key = 'EIZ';
          break;
        case 'N':
          key = 'EIN';
          break;
        case 'E':
          key = 'EIE';
          break;
        default:
          break;
      }
      if (_key !== 'X') {
        data[key] = _data[_key];
      } else {
        intensity = _data[_key];
      }
    });
    if (checkData()) {
      cb(data);
      data = {};
    }
  };
  return push;
};

const push = formatData((data) => {
  const dataSource = {};
  for (const key in data) {
    if (Object.prototype.hasOwnProperty.call(data, key)) {
      const element = data[key];
      dataSource[key] = element.reduce((prev, cur) => {
        if (cur[0] % 100 === 0) {
          let value = cur[1];
          if (isHighPassFilter.value) {
            value = cur[2];
          }
          cur[1] = value;
          prev.push(cur);
        }

        return prev;
      }, []);
    }
  }
  if (Object.keys(dataSource).length) {
    showBg.value = false;
  }
  renderChart(dataSource, intensity.toFixed(2));
});

const random = Math.random().toString().slice(-6);
const { connect, disconnect } = useEventSource(
  `/api/edge/sse/300/${random}/${code.value}`,
  {
    headers: {
      ['Authorization']: `Bearer ${userStore.token}`,
      'Content-Type': 'application/json',
      Accept: '*/*',
    },
    withCredentials: false,
    onMessage(res) {
      const data = JSON.parse(res);
      push(data);
    },
    onError(error) {
      console.log(error);
      disconnect();
    },
  },
);

onUnmounted(disconnect);

watch(
  () => [channels, isHighPassFilter],
  () => {
    updateChartConfig?.(toRaw(channels.value));
  },
  { deep: true },
);
</script>
